<?php


namespace app\controller;


use app\common\controller\ApiController;
use app\common\util\Response;
use app\model\Curd as CurdModel;
use think\App;
use think\response\Json;

class Curd extends ApiController
{
    protected $isValidate = false;
    private $model;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CurdModel();
    }

    /**
     * 列表
     * @return Json
     */
    public function list(): Json
    {
        $where = ['statua' => 1];
        $field = 'id,title,phone';
        $sort = 'id desc';
        $isPage = true;
        $data = $this->model->getList($where, $field, $sort, $isPage);
        return json($data);
    }

    /**
     * 新增
     * @return Json
     */
    public function create(): Json
    {
        $createData = [
            'title' => 'create',
            'phone' => '12345678910'
        ];
        $createModel = $this->model->create($createData);
        //自增id
        $idFieldName = $this->model->idFieldName;
        $id = $createModel->$idFieldName;
        //注意事项：不要用$this->model多次新增
        return Response::successJson();
    }

    /**
     * 更新
     * @return Json
     * @throws \app\common\exception\UpdateFailException
     */
    public function update(): Json
    {
        $id = 1;
        $where = [$this->model->idFieldName => $id, 'status' => '1'];
        $updateData = [
            'title' => 'update'
        ];

        //更具主键id更新
        $this->model->updateDataById($id, $updateData);
        //更新状态
        $this->model->updateStatus($id, 1, 0);
        //更新数据，要有影响行数
        $this->model->updateNeedAffectedRows($where, $updateData);
        return Response::successJson();
    }

    /**
     * 删除
     * @return Json
     */
    public function delete(): Json
    {
        $id = 1;
        //如果需要另外加删除条件
        $where = [];
        //如果需要另外加更新数据
        $uData = [];
        //软删除
        $this->model->softDelete($id, $where, $uData);
        return Response::successJson();
    }
}